#!/bin/bash
set -e

#================================================================================================================#
# 功能：用于更新阿里云域名IP，实现DDNS功能
#================================================================================================================#
#
# 使用方法：
#
# 方法1. 外部参数
# 修改源码，将对应参数 修改为$1,$2,$3,$4,$5,$6 
# aliddns.sh <aliddns_ak> <aliddns_sk> <aliddns_subdomain> <aliddns_domain> <aliddns_iptype> <aliddns_ttl>
# 示例(A 代表 IPv4，AAAA 代表 IPv6):
# 执行：aliddns.sh "xxxx" "xxx" "test" "mydomain.site" "A" 600
# 执行：aliddns.sh "xxxx" "xxx" "test" "mydomain.site" "AAAA" 600
#
# 方法2. 内部参数
# 修改源码, 将$1,$2,$3,$4,$5,$6 替换为对应参数
# 
# 示例: 
# aliddns_ak="xxxx"
# aliddns_sk="xxx"
# aliddns_subdomain="test"
# aliddns_domain="mydomain.site"
# aliddns_iptype="A"
# aliddns_ttl=600 
# 执行：aliddns.sh
#
#================================================================================================================#

#--------------------------------------------------------------
# 参数
#
# (*)阿里云 AccessKeyId
aliddns_ak=xxx
# (*)阿里云 AccessKeySecret
aliddns_sk=xxxxxx


# (*)域名：test.mydomain.com 
aliddns_subdomain=test #'test'
aliddns_domain=mydomain.com #'mydomain.com'

# (*)ip地址类型：'A' 或 'AAAA'，代表ipv4 和 ipv6
aliddns_iptype=AAAA # 'A' 或 'AAAA'，代表ipv4 和 ipv6

# TTL 默认10分钟 = 600秒 
aliddns_ttl=600 #"600"

#--------------------------------------------------------------


# --------------------------------------------------------------------------------------------------
# 函数
#
# 输出分割行
function line() {
    echo -e "\033[33m#################### ${1} ##################\033[0m"
}

# 命令检查
function check() {
    if [[ $? == 0 ]]; then
        echo -e "\033[32m${1} --------> success\033[0m";
    else
        echo -e "\033[31m${1} --------> fail\033[0m"; exit 0;
    fi
}

# 输出一些信息
function output() {
    echo -e "\033[32m${1}\033[0m";
}

# 获取 ipv4 地址
function getMachineIPv4() {
    echo $(/usr/bin/wget -qO- -t1 -T2 http://ip.3322.net)
}

# 获取 ipv6 地址
function getMachineIPv6() {
    ipv6=$(ip addr | grep "inet6.*global" | grep -v "deprecated" | awk '{print $2}' | awk -F"/" '{print $1}' | sed -n '1,1p')
    echo ${ipv6}
}

# 获取当前映射的 ip
function getDDNSIP() {
    current_ip=$(nslookup -query=${aliddns_iptype} ${aliddns_name} | grep "Address" | grep -v "#53" | awk '{print $2}')
    echo ${current_ip}
}

# url 编码
function urlencode() {
    # urlencode <string>
    out=""
    while read -n1 c
    do
        case ${c} in
            [a-zA-Z0-9._-]) out="${out}${c}" ;;
            *) out="$out`printf '%%%02X' "'${c}"`" ;;
        esac
    done
    echo -n ${out}
}

function enc() {
    echo -n ${1} | urlencode
}

function sendRequest() {
    local args="AccessKeyId=${aliddns_ak}&Action=${1}&Format=json&${2}&Version=2015-01-09"
    local hash=$(echo -n "GET&%2F&$(enc "${args}")" | openssl dgst -sha1 -hmac "${aliddns_sk}&" -binary | openssl base64)
    curl -s "http://alidns.aliyuncs.com/?${args}&Signature=$(enc "${hash}")"
}

function getRecordid() {
    grep -Eo '"RecordId":"[0-9]+"' | cut -d ':' -f2 | tr -d '"'
}

function queryRecordid() {
    sendRequest "DescribeSubDomainRecords" "SignatureMethod=HMAC-SHA1&SignatureNonce=${timestamp}&SignatureVersion=1.0&SubDomain=${aliddns_name}&Timestamp=${timestamp}&Type=${aliddns_iptype}"
}

function updateRecord() {
    sendRequest "UpdateDomainRecord" "RR=${aliddns_subdomain}&RecordId=$1&SignatureMethod=HMAC-SHA1&SignatureNonce=${timestamp}&SignatureVersion=1.0&TTL=${aliddns_ttl}&Timestamp=${timestamp}&Type=${aliddns_iptype}&Value=$(enc ${machine_ip})"
}

function addRecord() {
    sendRequest "AddDomainRecord&DomainName=${aliddns_domain}" "RR=${aliddns_subdomain}&SignatureMethod=HMAC-SHA1&SignatureNonce=${timestamp}&SignatureVersion=1.0&TTL=${aliddns_ttl}&Timestamp=${timestamp}&Type=${aliddns_iptype}&Value=$(enc ${machine_ip})"
}
# --------------------------------------------------------------------------------------------------


machine_ip=""
ddns_ip=""
aliddns_record_id=""

if [[ ${aliddns_subdomain} = "@" ]]; then
    aliddns_name=${aliddns_domain}
else
    aliddns_name=${aliddns_subdomain}.${aliddns_domain}
fi

line "`date`"
output "domain name: ${aliddns_name}"

if [[ ${aliddns_iptype} == 'A' ]]; then
    machine_ip=$(getMachineIPv4) && output "curren IPv4: ${machine_ip}"
    aliddns_record_id=${aliddnsipv4_record_id}
else
    machine_ip=$(getMachineIPv6) && output "curren IPv6: ${machine_ip}"
    aliddns_record_id=${aliddnsipv6_record_id}
fi

ddns_ip=$(getDDNSIP) && output "ddns_ip: ${ddns_ip}"


if [[ ${machine_ip} == "" ]]; then
    output "machine_ip is empty!"; exit 0;
fi

if [[ ${machine_ip} == ${ddns_ip} ]]; then
    output "No need to update ddns mapping"; exit 0;
fi


output "start update ddns ..."

timestamp=`date -u "+%Y-%m-%dT%H%%3A%M%%3A%SZ"`

if [[ ${aliddns_record_id} == "" ]]; then
    aliddns_record_id=$(queryRecordid | getRecordid) || "record_id is empty";
    output "record_id: ${aliddns_record_id}"

    if [[ ${aliddns_iptype} = 'A' ]]; then
        aliddnsipv4_record_id=${aliddns_record_id}
    else
        aliddnsipv6_record_id=${aliddns_record_id}
    fi
fi


# add support ipv4(A) and ipv4(AAAA) record
if [[ ${aliddns_record_id} == "" ]]; then
    output "add record starting"

    aliddns_record_id=$(addRecord | getRecordid)

    if [[ ${aliddns_record_id} == "" ]]; then
        output "record_id is empty"
    else
        output "added record ${aliddns_record_id}"
    fi
else
    output "update record starting"
    updateRecord ${aliddns_record_id}
    output "updated record ${aliddns_record_id}"
fi
